import { Layout, Button, Space, message, Drawer, Input } from 'myselfantd';
import React, { useState, useCallback, useMemo, useRef } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
// import { getSpuPage, getSpuInfoById, addSpu, updateSpu, delSpu } from '../api';
import Base from './Base';
import Static from './Static';
import Dynamic from './Dynamic';

interface DataType {
  code: number;
  work: string;
  operateArea: number;
  operateDistance: number;
  taskEndTime: string;
  taskStatus: number;
  evaluationState: number;
  option: [];
}
const App: React.FC = () => {
  const ref = useRef<any>();
  const [staticData, setStaticData] = useState([]);
  const [dynamicData, setDynamicData] = useState([]);
  const [dialogData, setDialogData] = useState<any>({
    show: false,
    title: '',
    viewmode: 'add',
    data: '',
    request: false,
  });
  return (
    <>
      <Layout.PageTemplate
        pageRef={ref}
        title="设备品类"
        search={useMemo(
          () => ({
            template: [
              {
                name: 'name',
                render: () => <Input placeholder="请输入设备品类名称" showCount={false} />,
              },
            ],
            button: [
              <Button.Image
                type="primary"
                icon={'add'}
                onClick={() => {
                  setDialogData({
                    show: true,
                    title: '创建品类',
                    viewmode: 'add',
                    data: '',
                    request: false,
                  });
                }}
              >
                创建品类
              </Button.Image>,
            ],
          }),
          [],
        )}
        table={useMemo(
          () => ({
            template: [
              {
                title: '序号',
                width: 150,
                fixed: 'left',
                align: 'left',
                render: (text, record, index) => {
                  return index + 1;
                },
              },
              {
                title: '品类ID',
                width: 150,
                textWrap: 'word-break',
                align: 'left',
                dataIndex: 'id',
              },
              {
                title: '品类名称',
                width: 150,
                textWrap: 'word-break',
                align: 'left',
                dataIndex: 'name',
              },
              {
                title: '父级品类',
                width: 120,
                textWrap: 'word-break',
                ellipsis: true,
                align: 'left',
                dataIndex: 'categoryPath',
              },
              {
                title: '创建时间',
                width: 100,
                dataIndex: 'createTime',
                key: 'createTime',
              },
              {
                title: '更新时间',
                width: 100,
                textWrap: 'word-break',
                align: 'left',
                dataIndex: 'updateTime',
              },
              {
                title: '操作',
                width: 240,
                render: (_, record) => (
                  <Space size="middle">
                    <Button
                      type="link"
                      block
                      onClick={() =>
                        setDialogData({
                          show: true,
                          title: '查看品类',
                          viewmode: 'view',
                          data: _.id,
                          request: async () => {
                            // let { result } = await getSpuInfoById(_.id);
                            // return result;
                            return []
                          },
                        })
                      }
                    >
                      查看
                    </Button>
                    <Button
                      type="link"
                      block
                      onClick={() =>
                        setDialogData({
                          show: true,
                          title: '编辑品类',
                          viewmode: 'edit',
                          data: _.id,
                          request: async () => {
                            // let { result } = await getSpuInfoById(_.id);
                            // let { staticAttributes, dynamicAttributes } = result;
                            // setStaticData(staticAttributes || []);
                            // setDynamicData(dynamicAttributes || []);
                            // return result;
                            return []
                          },
                        })
                      }
                    >
                      编辑
                    </Button>
                    <Button
                      type="link"
                      block
                      onClick={async () => {
                        // let result = await delSpu(_.id);
                        // if (result && result.message === 'success') {
                        //   ref.current?.handleSearch();
                        //   message.success('删除成功');
                        // }
                      }}
                    >
                      删除
                    </Button>
                  </Space>
                ),
              },
            ] as ColumnsType<DataType>,
            data: {
              data: [] as ColumnsType<DataType>,
              page: { total: 0, pageSize: 20, current: 1 },
            },
          }),
          [],
        )}
        // request={useCallback(async (page: any, params: any) => {
        //   let defaultParams: any = {
        //     page: page.current,
        //     pageSize: page.pageSize,
        //   };
        //   let {
        //     result: { data, pageIndex, pageSize: newPageSize, total },
        //   } = await getSpuPage({ ...defaultParams, ...params });
        //   return {
        //     data,
        //     page: { total, pageSize: newPageSize, current: pageIndex },
        //   };
        // }, [])}
      />
      {dialogData.show && (
        <Drawer
          title={dialogData.title}
          placement="right"
          onClose={() => {
            setDialogData({
              show: false,
              title: '',
              viewmode: 'add',
              data: '',
              request: false,
            });
          }}
          visible={dialogData.show}
          width={'80%'}
          padding={0}
          request={dialogData.request}
          render={(data: any = {}) => {
            let { staticAttributes, dynamicAttributes, ...base } = data;
            return [
              <Base
                close={() => {
                  setDialogData({
                    show: false,
                    title: '',
                    viewmode: 'add',
                    data: '',
                    request: false,
                  });
                }}
                data={base}
                viewmode={dialogData.viewmode}
                onFinish={async (params: any) => {
                  if (dialogData.viewmode === 'add') {
                    if (!staticData.length) {
                      return message.info('请添加静态参数');
                    }
                    if (!dynamicData.length) {
                      return message.info('请添动态属性');
                    }

                    params.categoryId = params.categoryId[1];
                    params.staticAttributes = staticData.map((item: any) => {
                      let { sortkey, ...rest } = item;
                      return rest;
                    });
                    params.dynamicAttributes = [];
                    for (let i = 0; i < dynamicData.length; i++) {
                      let {
                        booleanEnums,
                        enums,
                        min,
                        max,
                        readWriteType,
                        stringResult,
                        unitId,
                        walkLength,
                        ...restAttrs
                      }: any = dynamicData[i];
                      params.dynamicAttributes[i] = {
                        ...restAttrs,
                      };
                      switch (restAttrs.type) {
                        case '1':
                          params.dynamicAttributes[i].attributeValue = {
                            unitId,
                            max,
                            min,
                            walkLength,
                          };
                          break;
                        case '2':
                          params.dynamicAttributes[i].attributeValue = {
                            stringResult,
                          };
                          break;
                        case '3':
                          let newBooleanEnums = booleanEnums.map((item: any) => {
                            let { sortkey, ...rest } = item;
                            return rest;
                          });
                          params.dynamicAttributes[i].attributeValue = {
                            booleanEnums: newBooleanEnums,
                          };
                          break;
                        case '4':
                          let newEnums = enums.map((item: any) => {
                            let { sortkey, ...rest } = item;
                            return rest;
                          });
                          params.dynamicAttributes[i].attributeValue = {
                            enums: newEnums,
                          };
                          break;
                      }
                    }
                    params.brandId = +params.brandId;
                    // let res = await addSpu(params);
                    // if (res.message === 'success') {
                    //   ref.current?.handleSearch();
                    //   setDialogData({
                    //     show: false,
                    //     title: '',
                    //     viewmode: 'edit',
                    //     data: '',
                    //     request: false,
                    //   });
                    //   message.success('创建成功');
                    // }
                  } else if (dialogData.viewmode === 'edit') {
                    if (!staticData.length) {
                      return message.info('静态参数不能为空');
                    }
                    if (!dynamicData.length) {
                      return message.info('动态属性不能为空');
                    }
                    params.id = data.id;
                    params.categoryId = data.categoryId;
                    params.staticAttributes = staticData;
                    params.dynamicAttributes = dynamicData;
                    params.brandId = +params.brandId;
                    params.code = data.code;
                    // let res = await updateSpu(params);
                    // if (res.message==='success') {
                    //   ref.current?.handleSearch();
                    //   setDialogData({
                    //     show: false,
                    //     title: '',
                    //     viewmode: 'add',
                    //     data: '',
                    //     request: false,
                    //   });
                    //   message.success('编辑成功');
                    // }
                  }
                }}
              >
                <Static
                  viewmode={dialogData.viewmode}
                  data={staticAttributes}
                  onChange={(val: []) => {
                    console.log(val, '----val');
                    setStaticData([...val]);
                  }}
                />
                <Dynamic
                  viewmode={dialogData.viewmode}
                  data={dynamicAttributes}
                  onChange={(val: []) => {
                    console.log(val, '----val');
                    setDynamicData([...val]);
                  }}
                />
              </Base>,
            ];
          }}
        />
      )}
    </>
  );
};

export default App;
